<?php
//    Import( '@.Unit.Common' );
/**
 * BlogModel
 * 迷你博客Model层。操作相关迷你博客的数据业务逻辑
 * @package Model::Blog
 * @version $id$
 * @copyright 2009-2011 SamPeng
 * @author SamPeng <sampeng87@gmail.com>
 * @license PHP Version 5.2 {@link www.sampeng.cn}
 */
 
class NoteModel extends Model {


    public function _initialize() {
    //初始化只搜索status为0的。status字段代表没被删除的
     //   $this->status = 1;
        //$emotion_obj  = D( 'Smile' );
     //   $config_obj   = D( 'AppConfig' );
        ////获取配置
     //   $config = $config_obj->getConfig( APP_NAME );
     //   $config = self::changeType( $config,'int' ); //将数组各元素转换成int类型
      //  $this->setConfig( $config );
     //   parent::_initialize();
    }

    public function setCount($appid,$count) {
        $map['id'] = $appid;
        $map2['commentCount'] = $count;
        return $this->where($map)->save($map2);
    }
    /**
     * getBlogList
     * 通过userId获取到用户列表
     * 通过用户Id获取用户心情
     * @param array|string|int $userId
     * @param array|object $options 查询参数
     * @access public
     * @return object|array
     */
    public function getNoteList($map = null,$field=null,$order = null,$limit = 5) {
    //处理where条件
	    $map = $this->merge( $map );
        //连贯查询.获得数据集
       // $limit = isset( $limit )?$limit:$this->config->limitpage;
       // $result         = $this->where( $map )->field( $field )->order( $order )->find() ;
        import("@.ORG.Page"); //导入分页类
		$count = $this->count();//    计算总数
		$p = new Page ( $count, 8 );
        $condition['u_id'] = $u_id;
		$list=$this->where($condition)->limit($p->firstRow.','.$p->listRows)->order('ctime desc')->findAll();
		$p->setConfig('header','条记录');
		$p->setConfig('prev',"<");
		$p->setConfig('next','>');
		$p->setConfig('first','<<');
		$p->setConfig('last','>>');
        $page = $p->show();
	     $result['page']=$page;
         $result['list']=$list;
        
        
        //对数据集进行处理
       // $data           = $result['data'];
      //  $data           = $this->replace( $data ); //本类重写父类的replace方法。替换日志的分类和追加日志的提及到的人
        //$data           = intval( $this->config->replay ) ? $this->appendReplay($data):$data;//追加回复
		//dump ($data);
      //  $result['data'] = $data;
        
     	return $result;
    }


/**
 * 取得某篇日志的详情内容
 * @author agui
 */
public function getNoteInfo($n_id){
    if(empty($n_id)){
        return '参数错误';
    }
    $map['n_id']=$n_id;
    $result  = $this->where( $map )->find() ;
     return   $result; 
    
}


    /**
     * getBlogContent
     * 重写父类的getBlogContent
     * @param mixed $id
     * @param mixed $how
     * @param mixed $uid
     * @access public
     * @return void
     */
    public function getBlogContent( $id,$how =null,$uid = null  ) {
        $result         = parent::getBlogContent( $id,$how,$uid );
        if(false == $result) return false;
        $result['role']  = $this->checkCommentRole( $result['canableComment'],$uid,$this->cuid );
        $result['title'] = stripslashes( $result['title'] );
        $result['attach'] = unserialize($result['attach']);
        return $result;
    }

    public function setUid($value) {
        $this->cuid = $value;
    }
    
    
   
  /**
 ** merge 
  * 合并条件
  * @param mixed $map 
  * @access private
  * @return void
  */
   protected function merge ( $map = null ){
            if( isset( $map ) ){
                $map = array_merge( $this->data,$map );
            }else{
                $map = $this->data;
            }

            return $map;
        }
    public function getAllData($order){
                //TODO 根据条件决定排序方式,尚有优化空间
            $temp_order_map = $this->getOrderMap($order);
            //根据以上处理条件获取数据集
            $result             = $this->getBlogList($temp_order_map['map'],null,$temp_order_map['order']);
            $result['category'] = $this->getCategory();
            return $result;
    }
    public function getFollowsBlog($mid){
    	$fl=D("Follow");
        $followlist=$fl->getfollowList($mid);
                		//dump ($followlist);
                		foreach($followlist as $key=>$value)
						{
 							 $folist[$key]=$value['fid'];
						} 
                		$map['uid']  = array('in',$folist);
                		$order = 'cTime DESC';
            $result             = $this->getBlogList($map,null,$order);
            $result['category'] = $this->getCategory();
            return $result;	
    }
    private function getOrderMap($order){
           switch( $order ) {
                case 'hot':    //推荐阅读
                    $map['isHot'] = 1;
                    $order        = 'rTime DESC';
                    break;
                case 'new':    //最新排行
                    $order = 'cTime DESC';
                    break;
                case 'popular':    //人气排行
                    $order        = 'hot DESC';
                    $map['cTime'] = self::_orderDate( $this->config->allorder );//取得时间
                    break;
                case 'read':   //阅读排行
                    $order = 'readCount DESC';
                    $map['cTime'] = self::_orderDate( $this->config->allorder );//取得时间
                    break;
                case 'comment':   //评论排行
                    $order = 'commentCount DESC';
                    $map['cTime'] = self::_orderDate( $this->config->allorder );//取得时间
                    break;

                default:      //默认时间排行
                    $order = 'cTime DESC';
            }
            $map['private'] = array('neq',2);
            $result['map'] = $map;
            $result['order'] = $order;
            return $result;
    }
  
    public function getBlogCount($uid,$list) {
        $result = $list;
        $count = $this->getBlogCategoryCount( $uid );
        //重组数据
        $count_arr = array();
        foreach ( $count as $value ) {
            $count_arr[$value['category']] = $value['count'];
        }
        foreach ($result as &$value) {
            $value['count'] = $count_arr[$value['id']] ? $count_arr[$value['id']] : 0;
        }
        return $result;
    }
   

    /**
     * changeCount
     * 修改日志的浏览数
     * @param mixed $blogid
     * @access public
     * @return void
     */
    public function changeCount( $blogid ) {
        $sql = "UPDATE {$this->tablePrefix}blog
                    SET readCount=readCount+1,hot = commentCount*readCount+round(readCount/(commentCount+1),0)
                    WHERE id='$blogid' LIMIT 1 ";
        $result = $this->execute($sql);
        if ( $result ) {
            return true;

        }
        return false;
    }

       /**
     * updateAuto
     * 更新日志的列表
     * @param mixed $map
     * @param mixed $id
     * @access public
     * @return void
     */
    public function updateAuto( $map,$id ) {
        $outline = self::factoryModel( 'outline' );
        return $outline->doUpdateOutline( $map,$id );

    }
    /**
     * autosave
     * 自动保存
     * @param mixed $map
     * @access public
     * @return void
     */
    public function autosave( $map ) {
        $outline = self::factoryModel( 'outline' );
        return $outline->doAddOutline( $map );
    }
    /**
     * getConfig
     * 获取配置
     * @param mixed $index
     * @access public
     * @return void
     */
    public function getConfig( $index ) {
        $config = $this->config->$index;
        return $config;
    }


    /**
     * unsetConfig
     * 删除配置
     * @param mixed $index
     * @param mixed $group
     * @access public
     * @return void
     */
    public function unsetConfig( $index , $group = null ) {
        if( isset( $group ) ) {
            unset( $this->config->$group->$index );
        }else {
            unset( $this->config->$index );
        }
        return $this;
    }

    /**
     * DateToTimeStemp
     * 时间换算成时间戳返回
     * @param mixed $stime
     * @param mixed $etime
     * @access public
     * @return void
     */
    public function DateToTimeStemp( $stime,$etime ) {
        $stime = strval( $stime );
        $etime = strval( $etime );

        //如果输入时间是YYMMDD格式。直接换算成时间戳
        if( isset( $stime[7] ) && isset( $etime[7] ) ) {
        //开始时间
            $syear  = substr( $stime,0,4 );
            $smonth = substr( $stime,4,2 );
            $sday   = substr( $stime,6,2 );
            $stime  = mktime( 0, 0, 0, $smonth,$sday,$syear );

            //结束时间
            $eyear  = substr( $etime,0,4 );
            $emonth = substr( $etime,4,2 );
            $eday   = substr( $etime,6,2 );
            $etime  = mktime( 0, 0, 0, $emonth,$eday,$eyear );

            return array( 'between',array( $stime,$etime ) );
        }

        //如果输入时间是YYYYMM格式
        $start_temp   = $this->paramData( $stime );
        $end_temp     = $this->paramData( $etime );
        $start        = $start_temp[0];
        $end          = $end_temp[1];

        return array( 'between',array( $start,$end ) );
    }

       /**
     * changeType
     * 将数组中的数据转换成指定类型
     * @param mixed $data
     * @param mixed $type
     * @access private
     * @return void
     */
    private static function changeType( $data , $type ) {
        $result = $data;

        switch( $type ) {
            case 'int':
                $method = "intval";
                break;
            case 'string':
                $method = "strtval";
                break;
            default:
                throw new ThinkException( '暂时只能转换数组和字符串类型' );
        }
        foreach ( $result as &$value ) {
            is_numeric( $value ) && $value = $method( $value );
        }
        return $result;
    }


    private function replaceSpecialChar($code) {
        $code = str_replace("&amp;nbsp;", "", $code);

        $code = str_replace("<br>", "", $code);

        $code = str_replace("<br />", "", $code);

        $code = str_replace("<P>",  "", $code);

        $code = str_replace("</P>","",$code);

        return trim($code);
    }
    /**
     * _orderDate
     * 解析日志排序时间区段
     * @param mixed $options
     * @access private
     * @return void
     */
    private function _orderDate( $options ) {
        if('all' == $options) return array('lt',time());
        $now_year  = intval( date( 'Y',time() ) );
        $now_month = intval( date( 'n',time() ) );
        $now_day   = intval( date( 'j',time() ) );

        //定义偏移量
        $month = self::_getExcursion($options, 'month');
        $year = self::_getExcursion($options, 'year');
        $day = self::_getExcursion($options, 'day');

        //换算时间戳
        $toDate = mktime( 0,0,0,$now_month-$month,$now_day-$day,$now_year-$year );
        //返回数组型数据集
        return array( "between",array( $toDate,time() ) );
    }
    private static function _getExcursion($options,$field){
        $excursion = array(
                            'one'   => array('month'=>1),
                           'three' => array('month'=>3),
                           'half'  => array('month'=>6),
                           'year'  => array('year'=>1),
                           'oneDay'=> array('day'=>1),
                           'threeDay'=>array('day'=>3),
                           'oneWeek'=>array('day'=>7),
                           );
        return isset($excursion[$options][$field])?$excursion[$options][$field]:0;
    }
}
